package me.zhangjin.lucene.demo.queries;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.FuzzyQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

public class FuzzyQueryTest {

    public static void main(String[] args) throws IOException {

        Path indexPath = Paths.get("indexdir/index");
        Directory dir = FSDirectory.open(indexPath);
        IndexReader reader = DirectoryReader.open(dir);
        IndexSearcher searcher = new IndexSearcher(reader);

        // 正确的是 Trump，此处拼写错误 Trmp
        Term term = new Term("title", "Trmp");

        // 构造一个模糊匹配
        // 它是对 Term 而言的，而不是 Phrase
        // 默认可以容忍 2 个字符
        FuzzyQuery fuzzyQuery = new FuzzyQuery(term, 2);

        // Query:title:Trmp~2
        System.out.println("Query:" + fuzzyQuery);

        // 返回前10条
        TopDocs tds = searcher.search(fuzzyQuery, 10);
        for (ScoreDoc sd : tds.scoreDocs) {
            // Explanation explanation = searcher.explain(query, sd.doc);
            // System.out.println("explain:" + explanation + "\n");
            Document doc = searcher.doc(sd.doc);
            System.out.println("DocID:" + sd.doc);
            System.out.println("id:" + doc.get("id"));
            System.out.println("title:" + doc.get("title"));
            System.out.println("文档评分:" + sd.score);
        }
        dir.close();
        reader.close();

    }

}
